package service;

import dao.WorkerDao;
import dao.impl.WorkerDaoImpl;
import org.apache.commons.beanutils.BeanUtils;
import pojo.Worker;
import util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.Map;

public class WorkerService {

    private WorkerDao workerDao = new WorkerDaoImpl();

    /**
     * 员工登录方法
     *
     * @param request
     * @param response
     */
    public void login(HttpServletRequest request, HttpServletResponse response) {
        // 获取前台登录信息
        String workerLoginName = request.getParameter("workerLoginName");
        String workerPassword = request.getParameter("workerPassword");
        // 转换为MD5加密密码
        workerPassword = MD5Util.MD55(workerPassword);
        Worker worker = workerDao.login(workerLoginName, workerPassword);
        //System.out.println(workerPassword);
        if (worker == null) {
            Integer loginerrorTimes = workerDao.findLoginerrorTimesByWorkerLoginName(workerLoginName);
            //增加对应用户名的错误登录次数
            workerDao.addWorekErrorloginTimesByWorkerLoginName(workerLoginName);
            LogUtil.addLog(workerLoginName + " 登录时密码错误,密码错误第" + (loginerrorTimes+1) + "次", request, 0);
            Result.response(1003, "密码错误！", response);
        } else {
            // 查询详细的员工信息
            worker = workerDao.workerDetail(workerLoginName);
            //重置对应用户名的错误登录次数
            workerDao.resetWorekErrorloginTimesByWorkerLoginName(workerLoginName);
            // 将登录信息存入session
            request.getSession().setAttribute("worker", worker);
            LogUtil.addLog("登录管理系统", request);
            Result.response(200, "登录成功！", response, worker);
        }
    }

    public void getLoginerrorTimes(HttpServletRequest request, HttpServletResponse response) {
        // 获取前台登录信息
        String workerLoginName = request.getParameter("workerLoginName");
        String workerPassword = request.getParameter("workerPassword");
        // 数据验证
        if (!StringDataCheckUtil.check(workerLoginName, workerPassword)) {
            Result.response(1001, "登录参数有误！", response);
            return;
        }
        Worker worker = workerDao.findWorkerByName(workerLoginName);
        // 根据员工登录名查找员工
        if (worker == null) {
            LogUtil.addLog(workerLoginName + " 非法登录", request, 0);
            Result.response(1002, "该员工不存在！", response);
            return;
        }
        Integer loginerrorTimes = workerDao.findLoginerrorTimesByWorkerLoginName(workerLoginName);
        if (loginerrorTimes < 0) {
            Result.response(1001, "获取次数失败", response);
        }
        Result.response(200, "获取次数成功", response, loginerrorTimes);
    }


    /**
     * 获取用户权限的方法
     *
     * @param request
     * @param response
     */
    public void getPermission(HttpServletRequest request, HttpServletResponse response) {
        Worker worker = (Worker) request.getSession().getAttribute("worker");
        if (worker == null) {
            Result.response(1001, "获取权限失败！", response);
            return;
        }
        // 获取登录用户的权限信息
        String[] permissionSplit = worker.getDepartment().getDepartmentPermission().split("-");
        Integer[] workerPermission = new Integer[permissionSplit.length];
        for (int i = 0; i < permissionSplit.length; i++) {
            workerPermission[i] = (Integer.valueOf(permissionSplit[i]) - 1);
        }
        Result.response(200, "获取权限成功！", response, workerPermission);
    }

    /**
     * 添加员工的方法
     *
     * @param request
     * @param response
     */
    public void add(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取前端提交的数据
            Map<String, String[]> parameterMap = request.getParameterMap();
            Worker worker = new Worker();
            BeanUtils.populate(worker, parameterMap);
            worker.setWorkerCreateTime(new Timestamp(System.currentTimeMillis()));
            worker.setWorkerUpdateTime(new Timestamp(System.currentTimeMillis()));
            // 数据验证
            if (workerDao.findByLoginName(worker.getWorkerLoginName())) {
                Result.response(1002, "该登录名已存在！", response);
                return;
            }
            if (worker.getWorkerPhone().length() != 11) {
                Result.response(1003, "电话号码格式有误！", response);
                return;
            }
            if (worker.getWorkerIdCard().length() != 18) {
                Result.response(1004, "身份证号码格式有误！", response);
                return;
            }
            // 密码加密
            worker.setWorkerPassword(MD5Util.MD55(worker.getWorkerPassword()));
            // 添加
            if (workerDao.add(worker) > 0) {
                Result.response(200, "添加成功！", response);
                return;
            }
            Result.response(1001, "添加失败！", response);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }


    /**
     * 根据电话号码发送验证码
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void sendCodeByForgetWorkerPhone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String forgetWorkerPhone = request.getParameter("forgetWorkerPhone");
        if (workerDao.checkPhoneExist(forgetWorkerPhone)) {
            String relCode = SendCodeUtil.sendCode(forgetWorkerPhone);
            if ("".equals(relCode) && relCode == null) {
                Result.response(1001, "验证码发送失败", response);
            }
            Result.response(200, "验证码已下发，请耐心等待...", response, relCode);
        } else {
            Result.response(1002, "该号码员工不存在！", response);
        }
    }


    public void resetPasswordByForgetWorkerPhone(HttpServletRequest request, HttpServletResponse response) {
        String forgetWorkerPhone = request.getParameter("forgetWorkerPhone");
        String resetPassword = request.getParameter("resetPassword");
        if (workerDao.updateWorkerPasswordByWorkerPhone(forgetWorkerPhone, MD5Util.MD55(resetPassword)) <= 0) {
            Result.response(1001, "重置密码失败", response);
            LogUtil.addLog("重置密码失败,密码修改错误。员工电话尾号为[" + forgetWorkerPhone.substring(7) + "]", request, 0);
        }
        Result.response(200, "重置密码成功", response);
        LogUtil.addLog("电话尾号为[" + forgetWorkerPhone.substring(7) + "]的员工重置密码成功。", request, 1);
    }

}
